package com.example.androidhive.mat;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.androidhive.JSONParser;
import com.example.androidhive.R;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Polozenie2 extends Activity {

	// Progress Dialog
	private ProgressDialog pDialog;

	JSONParser jsonParser = new JSONParser();
	EditText mojekontohaslo_;

	// url to create new product
	private static String url_create_product ="http://opiekuj1.javaprovider.net/php/logowanie.php";
	private static String url_create_product2 ="http://opiekuj1.javaprovider.net/php/rezerwa.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private GoogleMap map; private LocationManager locationManager;
	// private LocationManager locationManager;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gmaps);
		 map = ((MapFragment) getFragmentManager()
					.findFragmentById(R.id.map)).getMap();
		 map.setPadding(0, 50, 0, 100);
		// map.setPadding(0, 50, 0, 100);
		// map.setOnMarkerClickListener(this);
		// map.
		// map.addMarker(new
		// MarkerOptions().position(LOCATION_BURNABY).title("TUT"));

		// Get a handle to the Map Fragment
		// GoogleMap map = ((MapFragment) getFragmentManager()
		// .findFragmentById(R.id.map)).getMap();

		// LatLng sydney = new LatLng(-33.867, 151.206);

		// map.setMyLocationEnabled(true);
		// map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

		// map.addMarker(new MarkerOptions()
		// .title("Sydney")
		// .snippet("The most populous city in Australia.")
		// .position(sydney));
		double lat,lon,latitude = 0;
		double longitude = 0;
		addd(50.98138, 18.21434, "mojdom");
	addd(51.00274, 18.15491, "smardy");
		// create marker
    if (map != null) {
        map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }

map.setMyLocationEnabled(true);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener loc_listener = new LocationListener() {

    public void onLocationChanged(Location l) {}

    public void onProviderEnabled(String p) {}

    public void onProviderDisabled(String p) {}

    public void onStatusChanged(String p, int status, Bundle extras) {}
};
//locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
location = locationManager.getLastKnownLocation(bestProvider);
try {
    lat = location.getLatitude();
    lon = location.getLongitude();
} catch (NullPointerException e) {
    lat = -1.0;
    lon = -1.0;
}
//Toast.makeText(this, "Myd"+lat+"-"+lon, Toast.LENGTH_LONG).show();
		/*
		 * 
		 * PolygonOptions rectOptions = new PolygonOptions() .add(new
		 * LatLng(37.35, -122.0), new LatLng(37.45, -122.0), new LatLng(37.45,
		 * -122.2), new LatLng(37.35, -122.2), new LatLng(37.35, -122.0));
		 */

		// Get back the mutable Polygon
		// Polygon polygon = map.addPolygon(rectOptions);

	}
	void addd(double a, double b, String c) {
		MarkerOptions marker = new MarkerOptions().position(new LatLng(a, b))
				.title(c);
		map.addMarker(marker);
	}
	void ff(String h){
		  TextView t=(TextView)findViewById(R.id.polozenie); 
	        t.setText(h);
	}
	  void rr(String h){
		  String youraddress="Kluczbork Jana Pawla II";
		  
		  String uri = "http://maps.google.com/maps/api/geocode/json?address=kluczbork,janapawlaII&sensor=false";
    HttpGet httpGet = new HttpGet(uri);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
        double lat= 0.0, lng= 0.0;
        lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lng");

        lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lat");
        TextView t=(TextView)findViewById(R.id.polozenie); 
        t.setText(String.valueOf(lat+" "+lng));
        //Log.d("latitude", lat);
        //Log.d("longitude", lng);
    } catch (JSONException e) {
        e.printStackTrace();
    }
	      
}
	class CreateNewProductR extends AsyncTask<String,String,String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Polozenie2.this);
			pDialog.setMessage("Rezerwowanie..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Creating product
		 * */
		protected String doInBackground(String... args) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("nazwa", "mm"));
			JSONObject json = jsonParser.makeHttpRequest(url_create_product2,
					"POST", params);
			
			// check log cat fro response
			Log.d("Create Response", json.toString());

			// check for success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
		}

	}
	/**
	 * Background Async Task to Create new product
	 * */
	class CreateNewProduct1 extends AsyncTask<String,String,String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Polozenie2.this);
			pDialog.setMessage("Logowanie..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Creating product
		 * */
		protected String doInBackground(String... args) {
			String name = mojekontohaslo_.getText().toString();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("nazwa", "mm"));
			JSONObject json = jsonParser.makeHttpRequest(url_create_product,
					"POST", params);
			
			// check log cat fro response
			Log.d("Create Response", json.toString());

			// check for success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					
					// closing this screen
					finish();
					//inputDesc =inputPrice =inputName = null;
				} else {
					// failed to create product
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
		}

	}
}

